package javabasics.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/15 11:48
 * @Version 1.0
 */
public class RandomAccessFileTest {

    /**
     * MappedByteBuffer 写耗时：52 ms
     * MappedByteBuffer 读耗时：44 ms
     * @param args
     */
    public static void main(String[] args) {
        // 写入数据大小
        int numOfInts = 4000000;

        Long startTime = System.currentTimeMillis();

//        writeFile(numOfInts);
//        System.out.println("MappedByteBuffer 写耗时：" + (System.currentTimeMillis() - startTime));

        readFile(numOfInts);
        System.out.println("MappedByteBuffer 读耗时：" + (System.currentTimeMillis() - startTime));

    }

    public static void writeFile(int numOfInts) {
        try {
            FileChannel fc = new RandomAccessFile("d:\\temp_mapped.tmp", "rw").getChannel();
            // 文件映射到内存
            IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, numOfInts * 4).asIntBuffer();
            // 写入文件
            for (int i = 0; i < numOfInts; i++) {
                ib.put(i);
            }
            if (fc != null) {
                fc.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readFile(int numOfInts) {
        try {
            FileChannel fc = new FileInputStream("d:\\temp_mapped.tmp").getChannel();
            IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).asIntBuffer();
            while (ib.hasRemaining()) {
                ib.get();
            }
            if (fc != null) {
                fc.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
